package apigateway.project.core.netty;

import apigateway.project.core.Config;
import apigateway.project.core.LifeCycle;
import apigateway.project.core.helper.AsyncHttpHelper;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.EventLoopGroup;
import lombok.extern.slf4j.Slf4j;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClientConfig;

import java.io.IOException;

/**
 * HTTP客户端启动类,主要用于下游服务的请求转发
 */
@Slf4j
public class NettyHttpClient implements LifeCycle {
    //异步高性能httpclient
    private AsyncHttpClient client;
    private final Config config;
    private EventLoopGroup eventLoopGroupWork;
    private DefaultAsyncHttpClientConfig.Builder clientBuilder;

    public NettyHttpClient(Config config, EventLoopGroup eventLoopGroupWork) {
        this.config = config;
        this.eventLoopGroupWork = eventLoopGroupWork;
        init();
    }


    /**
     * 初始化AsyncHttpClient
     */
    @Override
    public void init() {
        this.clientBuilder = new DefaultAsyncHttpClientConfig.Builder()
                .setFollowRedirect(false)
                .setEventLoopGroup(eventLoopGroupWork)
                .setConnectTimeout(config.getHttpConnectTimeout())
                .setRequestTimeout(config.getHttpRequestTimeout())
                .setMaxRequestRetry(config.getHttpMaxRequestRetry())
                .setAllocator(PooledByteBufAllocator.DEFAULT)
                .setCompressionEnforced(true)
                .setMaxConnections(config.getHttpMaxConnections())
                .setMaxConnectionsPerHost(config.getHttpConnectionPerHost())
                .setPooledConnectionIdleTimeout(config.getHttpPooledConnectionIdleTimeout());
    }

    @Override
    public void start() {
        DefaultAsyncHttpClientConfig buildConfig = clientBuilder.build();
        this.client = new DefaultAsyncHttpClient(buildConfig);
        //用辅助类来发消息
        AsyncHttpHelper.getInstance().initilize(client);
    }

    @Override
    public void shutdown() {
        if(client != null) {
            try {
                client.close();
            } catch (IOException e) {
                log.error("nettyHttpClient.shutdown() error", e);
            }
        }
    }
}
